package com.example.loganalysis.services;

import com.example.loganalysis.dao.TOperateLogDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Map;

@Service
public class OperateLogService {

    @Autowired
    private TOperateLogDao tOperateLogDao;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public OperateLogService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    public List<Map<String, Object>> getOperateLogs() throws Exception {
        String url = "http://192.168.231.60/api/v1/audits/operate-logs/";
        String token = "3faf3784857fdee03007987e8f41041b4dec6302";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Token " + token);

        // 创建 HttpEntity 并发送请求
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            return objectMapper.readValue(responseBody, List.class);
        } else {
            throw new RuntimeException("Failed to fetch Operate logs: " + response.getStatusCode());
        }
    }

    /*public void saveLoginLogs(List<Map<String, Object>> TLoginLogs, String ipfsHash) {
        // 将日志数据转换为 TLoginLog 对象列表
        List<TLoginLog> logs = TLoginLogs.stream().map(log -> {
            TLoginLog loginLog = new TLoginLog();
            loginLog.setDateTime((String) log.get("datetime")); // 确保字段名一致
            loginLog.setUsername((String) log.get("username"));
            loginLog.setIp((String) log.get("ip"));
            loginLog.setTypeDisplay((String) log.get("type_display"));
            loginLog.setStatusDisplay((String) log.get("status_display"));
            loginLog.setIpfsHash("QMsfnhksdjf");
            return loginLog;
        }).collect(Collectors.toList());

        // 调用批量插入方法
        if (!logs.isEmpty()) {
            tLoginLogDao.insertLoginLogs(logs); // 批量插入日志
        } else {
            throw new IllegalArgumentException("No valid login logs to save.");
        }
    }*/

}
